package com.wiiss.ams.cron;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.cronutils.model.CronType;
import com.cronutils.model.definition.CronDefinitionBuilder;
import com.cronutils.model.time.ExecutionTime;
import com.cronutils.parser.CronParser;

import java.time.LocalDateTime;
import java.time.ZonedDateTime;

public class Cron {

	private String expression;

	private ExecutionTime executionTime; // 计算执行时间的工具对象

	private LocalDateTime thisTime;

	private LocalDateTime lastTime; // 上次执行时间

	public static Cron of(String expression) {
		Cron cron = new Cron(expression);
		cron.executionTime = ExecutionTime.forCron(new CronParser(CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)).parse(expression));
		return cron;
	}

	// 触发 更新相关数据
	public void trigger() {
		thisTime = executionTime.lastExecution(ZonedDateTime.now()).get().toLocalDateTime(); // 当前执行时间
		lastTime = thisTime.plusSeconds(-LocalDateTimeUtil.between(thisTime, executionTime.nextExecution(ZonedDateTime.now()).get().toLocalDateTime()).getSeconds());
	}

	public LocalDateTime getThisTime() {
		return thisTime;
	}

	public LocalDateTime getLastTime() {
		return lastTime;
	}

	public String getExpression() {
		return expression;
	}

	private Cron(String expression) {
		super();
		this.expression = expression;
	}

}
